package de.baumann.browser.browser;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;

import com.tencent.smtt.export.external.interfaces.HttpAuthHandler;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.net.URISyntaxException;

import de.baumann.browser.R;
import de.baumann.browser.db.Record;
import de.baumann.browser.db.RecordAction;
import de.baumann.browser.views.widget.OdinToast;
import de.baumann.browser.web.OdinWebView;

@SuppressWarnings("ALL")
public class OdinWebViewClient extends WebViewClient {
    private final OdinWebView ninjaWebView;
    private final Context context;
    private final SharedPreferences sp;

    //    private final AdBlockJs adBlockJs;
    //    private final Cookie cookie;
    // Android版本变量
    private final int version = Build.VERSION.SDK_INT;

    private boolean white;

    public void updateWhite(boolean white) {
        this.white = white;
    }

    private boolean enable;

    public void enableAdBlock(boolean enable) {
        this.enable = enable;
    }

    public OdinWebViewClient(OdinWebView ninjaWebView) {
        super();
        this.ninjaWebView = ninjaWebView;

        this.context = ninjaWebView.getContext();
        this.sp = PreferenceManager.getDefaultSharedPreferences(context);
//        this.adBlockJs = new AdBlockJs(this.context);
        this.white = false;
        this.enable = true;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        ninjaWebView.onPageStart(view, favicon);
        ninjaWebView.getUiController().goBackEnable(true);
    }

    /**
     * 广告替换
     *
     * @param view
     * @param url
     */

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        ninjaWebView.getUiController().goForwardEnable(ninjaWebView.canGoForward());
        if (!ninjaWebView.getSettings().getLoadsImagesAutomatically()) {
            ninjaWebView.getSettings().setLoadsImagesAutomatically(true);
        }
        ninjaWebView.onPageFinished(view.getTitle(), url);

        RecordAction action = new RecordAction(context);

        action.open(true);

        if (action.checkHistory(url)) {
            action.deleteHistoryOld(url);
            action.addHistory(new Record(ninjaWebView.getTitle(), ninjaWebView.getUrl(), System.currentTimeMillis()));
        } else {
            action.addHistory(new Record(ninjaWebView.getTitle(), ninjaWebView.getUrl(), System.currentTimeMillis()));
        }

        action.close();

        if (ninjaWebView.isForeground()) {
            ninjaWebView.invalidate();
        } else {
            ninjaWebView.postInvalidate();
        }
    }

    @SuppressWarnings({"deprecation", "AliDeprecation"})
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
       if (url.startsWith("tbopen://") || url.startsWith("openapp")) {
            return false;
        }

//        if (!url.startsWith("http")) {
//            return false;
//        }
        final Uri uri = Uri.parse(url);
        return handleUri(view, uri);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        final Uri uri = request.getUrl();
        if (uri.toString().startsWith("tbopen://") || uri.toString().startsWith("openapp")) {
            return false;
        }
//        final Uri uri = request.getUrl();
//        if (!uri.toString().startsWith("http")) {
//            return false;
//        }
        return handleUri(view, request.getUrl());
    }

    private boolean handleUri(WebView webView, final Uri uri) {

        final String url = uri.toString();
        // Based on some condition you need to determine if you are going to load the url
        // in your web view itself or in a browser.
        // You can use `host` or `scheme` or any part of the `uri` to decide.
        // open web links as usual

        if (url.startsWith("http")) {
            return false;
        }

        //try to find browse activity to handle uri
        Uri parsedUri = Uri.parse(url);
        PackageManager packageManager = context.getPackageManager();
        Intent browseIntent = new Intent(Intent.ACTION_VIEW).setData(parsedUri);
        if (browseIntent.resolveActivity(packageManager) != null) {
            context.startActivity(browseIntent);
            return true;
        }
        //if not activity found, try to parse intent://
        if (url.startsWith("intent:")) {
            try {
                Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                if (intent.resolveActivity(context.getPackageManager()) != null) {
                    try {
                        context.startActivity(intent);
                    } catch (Exception e) {
                        OdinToast.show(context, R.string.toast_load_error);
                    }
                    return true;
                }
                //try to find fallback url
                String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                if (fallbackUrl != null) {
                    webView.loadUrl(fallbackUrl);
                    return true;
                }
                //invite to install
                Intent marketIntent = new Intent(Intent.ACTION_VIEW).setData(Uri.parse("market://details?id=" + intent.getPackage()));
                if (marketIntent.resolveActivity(packageManager) != null) {
                    context.startActivity(marketIntent);
                    return true;
                }
            } catch (URISyntaxException e) {
                //not an intent uri
            }
        }
        return true;//do nothing in other cases
    }

    /**
     * 广告屏蔽(广告拦截后可以顺手塞进去，但是这种效率差，而且需要得到宽高)
     *
     * @param view
     * @param url
     * @return
     */
    @Override
    @SuppressWarnings({"deprecation", "AliDeprecation"})
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
        return super.shouldInterceptRequest(view, url);
    }


    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        return super.shouldInterceptRequest(view, request);
    }

    @Override
    public void onFormResubmission(WebView view, @NonNull final Message doNotResend, final Message resend) {
    }

    @Override
    public void onReceivedSslError(WebView view, @NonNull final SslErrorHandler handler, SslError error) {
    }

    @Override
    public void onReceivedHttpAuthRequest(WebView view, @NonNull final HttpAuthHandler handler, String host, String realm) {
    }
}
